"""
Copyright © 2020 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/ESP32-BLE-MI_Temperature_Humidity_2_Reader
"""
import bluetooth as bt
from ble.tools import BLETools


MI_SERVICE_UUID = bt.UUID(0xFE95)


class MIOT(object):
	def __init__(self, data):
		self.addr_type = data[0]
		self.addr = bytes(data[1])
		self.adv_type = data[2]
		self.__rssi = data[3]
		self.__adv_data = data[4]
		self.name = BLETools.decode_name(self.__adv_data) or BLETools.decode_mac(self.addr)
		self.conn_handle = None


class MIOTFactory(object):
	def __init__(self):
		self.__miots = []
		self.__addrs = []
	
	def append(self, data):
		addr = bytes(data[1])

		if addr not in self.__addrs:
			self.__addrs.append(addr)
			self.__miots.append(MIOT(data))

	def clear(self):
		self.__addrs.clear()
		self.__miots.clear()

	def count(self):
		return len(self.__miots)

	def find(self, addr=None, conn_handle=None):
		if addr:
			try:
				index = self.__addrs.index(bytes(addr))
				return self.__miots[index]
			except ValueError:
				return None
		elif conn_handle is not None:
			for device in self.__miots:
				if device.conn_handle == conn_handle:
					return device
		else:
			return None

	def devices(self):
		return self.__miots

	@staticmethod
	def check(adv_data):
		"""
		Check if it's a MIOT device
		"""
		return True if MI_SERVICE_UUID in BLETools.decode_services_data(adv_data)[0] else False
